﻿using System;
using System.Collections.Generic;
using System.Linq;

using Csla;

using HHB.DataAccess;
using HHB.DataAccess.Entities;

namespace HHB.Domain.Users
{
    public class UserInfoList : ReadOnlyListBase<UserInfoList, UserInfo>
    {
        public static UserInfoList Get()
        {
            return DataPortal.Fetch<UserInfoList>();
        }         
        public static UserInfoList Get(string usernameStartsWith)
        {
            return DataPortal.Fetch<UserInfoList>(usernameStartsWith);
        }

        public UserInfoList()
        {
        }
        private void DataPortal_Fetch()
        {
            this.DataPortal_Fetch(null);
        }

        private void DataPortal_Fetch(string usernameStartsWith)
        {
            using (var context = new HhbContext())
            {
                IQueryable<User> entities = context.Users;

                if (usernameStartsWith != null)
                {
                    entities = entities.Where(e => e.Username.StartsWith(usernameStartsWith));
                }

                var children = entities.ToArray().Select(UserInfo.Get);

                this.IsReadOnly = false;
                this.RaiseListChangedEvents = false;

                this.AddRange(children);

                this.IsReadOnly = true;
                this.RaiseListChangedEvents = true;

            }

        }
    }
}